<template>
  <div class="account-container">
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" class="demo-form-inline">
        <el-form-item label="账号" class="el-form-item">
          <el-input v-model="filterForm.phone" maxlength="11" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="授权名称" class="el-form-item">
          <el-input v-model="filterForm.username" placeholder="请输入授权名称" />
        </el-form-item>
        <el-form-item label="营业执照" class="el-form-item">
          <el-input v-model="filterForm.business_license_name" placeholder="请输入营业执照名称" />
        </el-form-item>
        <el-form-item label="法人姓名" class="el-form-item">
          <el-input v-model="filterForm.legal_person_name" placeholder="请输入法人姓名" />
        </el-form-item>
        <el-form-item label="法人电话" class="el-form-item">
          <el-input v-model="filterForm.legal_person_phone" maxlength="11" placeholder="请输入法人电话" />
        </el-form-item>
        <el-form-item label="联系人姓名" class="el-form-item">
          <el-input v-model="filterForm.contact_person_name" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人电话" class="el-form-item">
          <el-input v-model="filterForm.contact_person_phone" maxlength="11" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="合作属性" class="el-form-item">
          <el-select v-model="filterForm.roleId" placeholder="全部">
            <el-option v-for="role in roleList" :key="role.id" :label="role.name" :value="role.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" class="Button">查询</el-button>
          <el-button @click="resetForm" class="Button">重置</el-button>
           <el-button type="primary" @click="handleDowlist" class="Button DowBtn">
          <el-icon class="el-icon--left"><Download /></el-icon>导出账号
        </el-button>
       
      </el-form-item>
       
      </el-form>
    </div>

    <el-table :data="tableData.filter((item) => item.examEnabled)" border class="elTable">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="phone" label="账号" width="120" />
      <el-table-column prop="username" label="授权名称" width="250" />

      <el-table-column prop="roleId" label="合作属性" width="100">
        <template #default="scope">
          <span>{{ scope.row.role?.name || '未知角色' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="province_city_district" label="省市区" width="200" />
      <el-table-column prop="address_detail" label="详细地址" width="300" />
      <el-table-column prop="business_license_name" label="营业执照全称" width="300" />

      <el-table-column prop="legal_person_name" label="法人姓名" width="100" />
      <el-table-column prop="legal_person_phone" label="法人电话" width="120" />
      <el-table-column label="操作" width="400" fixed="right">
        <template #default="scope">
          <div class="button-container">
            <el-button type="primary" size="small" class="action-btn" @click="handleView(scope.row)">查看</el-button>
            <el-button type="primary" size="small" class="action-btn" :disabled="mainStore.userInfo.id == scope.row.id" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="success" size="small" class="action-btn" :disabled="!scope.row.registrationForm" @click="handleDownloadRegistration(scope.row)">
              <el-icon class="el-icon--left"><Download /></el-icon>登记表
            </el-button>
            <el-button type="warning" size="small" class="action-btn" @click="handleChangePassword(scope.row)">修改密码</el-button>
            <el-button :type="scope.row.opendId ? 'danger' : 'success'" size="small" class="action-btn" @click="handleWechatBinding(scope.row)">
              {{ scope.row.opendId ? '解绑微信' : '绑定微信' }}
            </el-button>
          </div>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100,200]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper" />
    </div>

    <ViewUserDialog ref="viewDialogRef" :role-list="roleList" />

    <!-- 添加修改密码弹框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="80px" class="password-form">
        <el-form-item label="账号">
          <el-input v-model="passwordForm.phone" disabled />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="passwordForm.password" type="password" placeholder="请输入新密码" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange" :loading="passwordLoading"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加二维码弹窗 -->
    <el-dialog v-model="qrcodeDialogVisible" title="微信绑定" width="300px" center>
      <div class="qrcode-container">
        <img v-if="currentQRCode" :src="imgUrls(currentQRCode)" class="qrcode-img" />
        <p class="qrcode-tip">请使用微信扫描二维码进行绑定</p>
      </div>
    </el-dialog>

    <EditUserDialog ref="editDialogRef" :role-list="roleList" @update="getSubuser" />
  </div>
</template>

<script setup>
  import { imgUrls } from '@/utils/utils';
  import { ref, onMounted } from 'vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import Http from '@/utils/http';
  import { exportUserList } from '@/utils/Api';
  import EditUserDialog from '@/components/EditUserDialog.vue';
  import ViewUserDialog from '@/components/ViewUserDialog.vue';
  import { Download } from '@element-plus/icons-vue';
  import { useMainStore } from '@/stores/useMain';
  
  const mainStore = useMainStore();
  const filterForm = ref({
    phone: '',
    roleId: '',
    username: '',
    business_license_name: '',
    legal_person_name: '',
    legal_person_phone: '',
    contact_person_name: '',
    contact_person_phone: '',
  });

  const tableData = ref([]);
  const roleList = ref([]);
  const viewDialogRef = ref(null);

  const dialogVisible = ref(false);
  const formRef = ref();
  const form = ref({
    phone: '',
    username: '',
    roleId: '',
    password: '678678',
    examEnabled: false,
    showEnabled: false,
  });

  // 添加分页相关的响应式变量
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);

  onMounted(() => {
    getSubRole();
    getSubuser();
  });

  const rules = {
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
    username: [{ required: true, message: '请输入账号名称', trigger: 'blur' }],
    roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  };

  const getSubRole = async () => {
    const { code, data, msg } = await Http.get({
      url: '/yp_admin/getSubRole',
    });
    if (code != 200) return ElMessage.error(msg);
    roleList.value = [{ id: '', name: '全部' }, ...data];
  };

  const getSubuser = async () => {
    const { code, data, msg } = await Http.get({
      url: '/yp_admin/getSubuser',
      params: {
        ...filterForm.value,
        page: currentPage.value,
        pageSize: pageSize.value,
      },
    });
    if (code != 200) return ElMessage.error(msg);
    tableData.value = data.list;
    total.value = data.total;
  };

  const handleSearch = () => {
    getSubuser();
  };

  const resetForm = () => {
    filterForm.value = {
      phone: '',
      roleId: '',
      username: '',
      business_license_name: '',
      legal_person_name: '',
      legal_person_phone: '',
      contact_person_name: '',
      contact_person_phone: '',
    };
    currentPage.value = 1;
    handleSearch();
  };

  const editDialogRef = ref(null);

  const handleEdit = (row) => {
    editDialogRef.value?.open(row);
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm('确定要删除该账号吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const { code, msg } = await Http.post({
            url: '/yp_admin/deleteUser',
            data: { id: row.id },
          });
          if (code === 200) {
            ElMessage.success('删除成功');
            getSubuser(); // 刷新表格数据
          } else {
            ElMessage.error(msg || '删除失败');
          }
        } catch (error) {
          console.error('删除账号失败:', error);
          ElMessage.error('删除失败');
        }
      })
      .catch(() => {
        // 取消删除，不做任何操作
      });
  };

  const loading = ref(false);

  const submitForm = async () => {
    if (!formRef.value) return;
    if (loading.value) return;

    await formRef.value.validate(async (valid) => {
      if (valid) {
        loading.value = true;
        try {
          const { code, msg } = await Http.post({
            url: '/yp_admin/addUser',
            data: form.value,
          });
          if (code === 200) {
            ElMessage.success('添加成功');
            dialogVisible.value = false;
            getSubuser(); // 刷新表格数据
          } else {
            ElMessage.error(msg || '添加失败');
          }
        } catch (error) {
          console.error('添加账号失败:', error);
          ElMessage.error('添加失败');
        } finally {
          loading.value = false;
        }
      }
    });
  };

  const handleView = (row) => {
    viewDialogRef.value?.open(row);
  };

  const handleDownloadRegistration = async (row) => {
    try {
      if (!row.registrationForm) {
        return;
      }
      const fileUrl = imgUrls(row.registrationForm);
      window.open(fileUrl, '_blank');
      ElMessage.success('下载成功');
    } catch (error) {
      console.error('下载失败:', error);
      ElMessage.error('下载失败');
    }
  };

  // 添加新的响应式变量
  const passwordDialogVisible = ref(false);
  const passwordFormRef = ref();
  const passwordForm = ref({
    id: '',
    phone: '',
    username: '',
    password: '',
  });
  const passwordLoading = ref(false);

  const passwordRules = {
    password: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    ],
  };

  // 处理修改密码按钮点击
  const handleChangePassword = (row) => {
    passwordForm.value = {
      id: row.id,
      phone: row.phone,
      username: row.username,
      password: '',
    };
    passwordDialogVisible.value = true;
  };

  // 提交密码修改
  const submitPasswordChange = async () => {
    if (!passwordFormRef.value) return;

    await passwordFormRef.value.validate(async (valid) => {
      if (valid) {
        passwordLoading.value = true;
        try {
          const { code, msg } = await Http.post({
            url: '/yp_admin/updateUser',
            data: {
              id: passwordForm.value.id,
              password: passwordForm.value.password,
            },
          });
          if (code === 200) {
            ElMessage.success('密码修改成功');
            passwordDialogVisible.value = false;
          } else {
            ElMessage.error(msg || '修改失败');
          }
        } catch (error) {
          console.error('修改密码失败:', error);
          ElMessage.error('修改失败');
        } finally {
          passwordLoading.value = false;
        }
      }
    });
  };

  const qrcodeDialogVisible = ref(false);
  const currentQRCode = ref('');

  // 处理微信绑定/解绑
  const handleWechatBinding = async (row) => {
    if (row.opendId) {
      // 解绑微信
      ElMessageBox.confirm('确定要解绑微信吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const { code, msg } = await Http.post({
            url: '/yp_admin/unbindOpenId',
            data: {
              userId: row.id,
            },
          });
          if (code === 200) {
            ElMessage.success('解绑成功');
            getSubuser(); // 刷新表格数据
          } else {
            ElMessage.error(msg || '解绑失败');
          }
        } catch (error) {
          console.error('解绑失败:', error);
          ElMessage.error('解绑失败');
        }
      });
    } else {
      // 显示绑定二维码
      if (!row.QRcode) {
        return ElMessage.warning('未获取到二维码');
      }
      currentQRCode.value = row.QRcode;
      qrcodeDialogVisible.value = true;
    }
  };

  // 添加分页处理方法
  const handleSizeChange = (val) => {
    pageSize.value = val;
    getSubuser();
  };

  const handleCurrentChange = (val) => {
    currentPage.value = val;
    getSubuser();
  }; // 导出账号列表

  const handleDowlist = async () => {
    if (!tableData.value.length) {
      ElMessage.warning('暂无数据可导出');
      return;
    }
    const requetObj = {
      ...filterForm.value,
      moduleType: 1,
    };
    exportUserList(requetObj);
  };
</script>

<style scoped lang="scss">
  .el-form--inline .el-form-item {
    margin-right: 10px !important;
    margin-bottom: 10px !important;
  }
  .el-select,
  .el-input {
    width: 180px;
  }
  .DowBtn{
    margin-left: 10px !important;
  }
  :deep(.el-input__wrapper) {
    height: 40px;
    line-height: 40px;
  }
  :deep(.el-form-item__label) {
    width: 88px;
    height: 40px;
    line-height: 40px;
    padding-right: 12px;
    
 
  }

  .account-container {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    padding: 20px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
  }

  .filter-section {
    width: 100%;
    display: flex;
    align-content: center;
    .left {
      width: 100%;
      display: flex;
      .demo-form-inline {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
      }
    }
  }

  .elTable {
    width: 100%;
    flex: 1;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }

  .button-container {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .action-btn {
    min-width: 68px;
    padding: 4px 8px;
    font-size: 12px;
    height: 28px;
    white-space: nowrap;
    margin: 0;
    border-radius: 4px;
  }

  .qrcode-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
  }

  .qrcode-img {
    width: 200px;
    height: 200px;
    object-fit: contain;
  }

  .qrcode-tip {
    margin-top: 15px;
    color: #666;
    font-size: 14px;
  }

  .password-form {
    padding: 0 20px;
  }

  .password-form :deep(.el-form-item) {
    margin-bottom: 20px;
  }

  .password-form :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
</style>
